JavaScript Variables: var, let, const

Variables are fundamental to all programming languages. They act as containers for storing different types of data. Let's explore the different types of variables in JavaScript.

What is a Variable?

Variables store data, such as text strings or numbers. To create a variable, use the var, let, or const keyword. For example:


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Variables</title>
</head>
<body>
    <button class="button" onclick="example1()" >Run Example </button >
    <div id="output1" > </div >
    <Script>
        function example1() {
            var variableName = "Hello, this is a variable!";
            document.getElementById('output1').innerHTML = variableName;
        }
    </Script>
</body>
</html>
                  
                

Naming Conventions for Variables

Naming conventions for JavaScript variables are important for writing clear, maintainable, and understandable code. Here are some key guidelines and best practices for naming variables in JavaScript:

  • Use Meaningful Names Choose names that describe the purpose of the variable. This makes the code easier to read and understand. Example : totalPrice, userName, isLoggedIn
  • Follow Case Conventions JavaScript conventionally uses camelCase for variable names:
    camelCase: The first word is lowercase, and each subsequent word starts with an uppercase letter.
    Example: firstName, orderCount
  • Avoid Special Characters Variable names can only include letters, numbers, underscores (_), and dollar signs ($). They cannot start with a number and should avoid special characters (e.g. @, #, -).
  • Spaces are not allowed.
  • It cannot be a JavaScript keyword or reserved word.

Declaration of JavaScript Variables

There are three ways to declare variables:

1. Using var


                             
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class="button" onclick="example1()" >Run Example </button >
    <Script>
        function example2() { 
            var score = 80;
            function updateScore() {
                var score = 90;
                console.log(score); // Function-scoped
            }
            updateScore();
            document.getElementById('output2').innerHTML = "Check the console for var scoping.";
        }
     </Script>
</body>
</html>
                             
                         

Function-scoped variables:

var userName;
userName = "Akef Khan";

2. Using let and const (ES6)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>JavaScript Variable Scope Example (Let and Const) </h1>
    
    <p><strong>Character Name:</strong> <span id="characterName"></span></p>
    <p><strong>Character Age:</strong> <span id="characterAge"></span></p>
    <p><strong>Is Character a Student?</strong> <span id="isCharacterStudent"></span></p>
    <p><strong>Value of PI:</strong> <span id="piValue" ></span></p>
    <p id="constErrorMessage" style="color: red;"></p>
    <script>
        let characterName = "Khizar Mirza";
        let characterAge = 19;
        let isCharacterStudent = true;
        const PI = 3.14;
        // Displaying the values in the HTML page
        document.getElementById("characterName").innerText = characterName;
        document.getElementById("characterAge").innerText = characterAge;
        document.getElementById("isCharacterStudent").innerText = isCharacterStudent ? "Yes" : "No";
        document.getElementById("piValue").innerText = PI;
        // Attempting to reassign PI (This will cause an error)
        try {
            PI = 10; // This will throw an error because PI is a const
        } catch (error) {
            // Catching the error and displaying the message in HTML
            document.getElementById("constErrorMessage").innerText = "Error: Cannot reassign a 'const' variable. PI is a constant.";
        }
    </Script>
</body>
</html>
                             
                         

Block-scoped variables:

PI = 10; // Error: Cannot reassign

Differences Between var, let, and const

  • Var: Traditional way, function-scoped, can be reassigned.
  • Let: ES6, block-scoped, can be reassigned but not re-declared in the same scope.
  • Const: ES6, block-scoped, cannot be reassigned.

Var Example


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>JavaScript Variable Scope Example (Let and Const) </h1>
    
    <p><strong>Global Score:</strong> <span id="globalScore"></span></p>
    <p><strong>Score Inside Function:</strong> <span id="functionScore"></span></p>
    <script>                    
        // Global variable
        var score = 80;
        // Display the global score
        document.getElementById("globalScore").innerText = score;
        // Function that changes the score inside its scope
        function updateScore() {
            var score = 90; // Function-scoped variable
            console.log("Inside function, score:", score); // Logs 90 inside the function
            // Display the score inside the function
            document.getElementById("functionScore").innerText = score;
        }
        // Call the function to update the score
        updateScore();
        // Log the global score after the function call
        console.log("Outside function, score:", score); // Logs 80 outside the function
    </Script>
</body>
</html>
                    

Let and Const Example


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>JavaScript Variable Scope Example (Let and Const) </h1>
    
    <p><strong>Value of count (outside block):</strong> <span id="countOutsideBlock""></span></p>
    <p><strong>Value of count (inside block):</strong> <span id="countInsideBlock"></span></p>
    <p><strong>Error message:</strong> <span id="constErrorMessage" style="color: red;"></span></p>
    <script>                    
        // Block-scoped variable with let
        let count = 10;
        
        // Display the value of count outside the block
        document.getElementById("countOutsideBlock").innerText = count;
        // Block scope (inside an if statement)
        if (true) {
            let count = 20; // A different 'count' variable inside the block
            document.getElementById("countInsideBlock").innerText = count; // 20 inside the block
            console.log("Inside block, count:", count); // Logs 20
        }
        console.log("Outside block, count:", count); // Logs 10
        // Constant variable PI
        const PI = 3.14;
        document.getElementById("constErrorMessage").innerText = "Error: Cannot reassign a constant variable (PI).";
        
        // Attempt to reassign PI (this will throw an error)
        try {
            PI = 4; // This will throw an error because PI is a constant
        } catch (error) {
            // Catching the error and displaying the message in the HTML
            console.log("Error: Cannot reassign a constant variable (PI).");
        }
    </Script>
</body>
</html>